<template>
  <el-container>
    <el-aside class="nopadding treesearch" style="width: 300px;background-color: #fff;" >
			<ex-search-tree ref="searchTree" :defaultwidth=300 :treeApi="this.$API.system.position.treeData" @changeHandler="searchTreeHandler" :param="{resourceType:'0'}" :title="title"></ex-search-tree>
		</el-aside>
      <el-container>
        <el-header>
      <div class="left-panel">
        <fsButton ref="button" plain size="default" :buttons="buttons" @clickHandler="buttonHandler"></fsButton>
      </div>
      <div class="right-panel">
        <ex-search ref="search" :searches="searches" @searchOk="searchHandler" default-code="positionName" placeholder="请输入位置名称"></ex-search>
      </div>
    </el-header>
        <el-main class="nopadding">
          <ex-table id="positionTable" ref="table" :columns="columns" :url="this.$API.system.position.list.url" :refs="this.$refs" search="search"
          @columnClick="columnClickHandler"
          @checkClick="checkClickHandler"></ex-table>
        </el-main>
      </el-container>
  </el-container>

  <save-dialog ref="saveDialog" @success="searchHandler"/>
  <admin-save-dialog ref="adminSaveDialog" @success="searchHandler"/>
  <view-dialog ref="viewDialog"/>

</template>

<script>
import saveDialog from './save'
import adminSaveDialog from '@/views/setting/position/save.vue'
import viewDialog from './view'
import ExTable from "@/components/exTable/index.vue";
import ExSearch from "@/components/exSearch/index.vue";
import ExSearchTree from "@/components/exSearchTree/index.vue";
import BaseTemplate from "@/utils/baseTemplate";

export default {
  name: '位置管理',
  components: {
	  viewDialog,
	  ExSearchTree,
	  ExSearch,
	  ExTable,
	  saveDialog,
	  adminSaveDialog,
  },
  data() {
    return {
      buttons: [
		  {name: '新增', icon: "el-icon-plus", click: "add", width:"70px",permission:"add"},
		  {name: this.$t('button.edit'), icon: "el-icon-edit", type: "parent",parent:true,show:"none",width:"70px",
			childrenbuttons:[
			  //{name: this.$t('button.edit'),  click: "edit",permission:"edit"},
			  {name: this.$t('button.delete'),  click: "del",permission:"delete"},
			  {name: '地区删除',  click: "adminDelete",permission:"adminDelete"},
			  {name: this.$t('button.enabled'),  click: "enabled",permission:"enabled"},
			  {name: this.$t('button.disabled'),  click: "disabled",permission:"disabled"},
			]},
        	{name: "...", type: "parent",parent:true,permission:"export",
			childrenbuttons:[
			    {name: this.$t('button.export'),  click: "export",permission:"export"},
				{name: '地区新增', click: "adminAdd",permission:"adminAdd"},
			]},
      ],
      searches: [
        { type: "input", name: "位置名称", code: "positionName", placeholder: "请输入位置名称", maxlength: 30, showLimit: true},
        { type: "input", name: "位置编码", code: "positionCode", placeholder: "请输入位置编码", maxlength: 30, showLimit: true},
        {type: "radio", name: "是否可用", code: "isEnabled",dictCode:'IS_ENABLED'},
      ],
      columns: [
      {code: "操作", name: "操作", width: "230",click:[
		  {label:"编辑",icon:"el-icon-edit-pen",event:'detailEdit',permission: "edit"},
		  {label:"地区编辑",icon:"el-icon-edit-pen",event:'adminDetailEdit',permission: "adminEdit"},
		  {label:"删除",icon:"el-icon-delete",event:'detaildel',permission: "delete"}
		  ]
	  },
      {code: "positionName", name: "名称", width: "300",color:'red',click:"show1"},
        {code: "positionCode", name: "编码", width: "200", sortable: true},
        {code: "positionAddress", name: "具体地址", width: "150"},
        {code: "isEnabled", name: "是否可用", width: "100", sortable: true, formatter: "DICT", key: "IS_ENABLED"},
        {code: "createUser", name: "创建人", width: "", formatter: "DICT", key: "SysUser"},
        {code: "createTime", name: "创建时间", width: "175", sortable: true, formatter: "DATETIME"},
      ],
      parentLevelCode: null,
		lastLevelAddress: '',
		positionType: null,
		isCanCreate:false,
		isOperation:true,
      title:"位置管理",

    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    checkClickHandler(value) {
      if(value==0){
        for (let index = 0; index < this.buttons.length; index++) {
          if(this.buttons[index].show!=undefined){
            this.buttons[index].show="none"
          }
        }
      }else{
        for (let index = 0; index < this.buttons.length; index++) {
          if(this.buttons[index].show!=undefined){
          this.buttons[index].show=""
          }
        }
      }
    },
    buttonHandler(index, name) {
      this.$options.methods[name](this, index);
    },
    async searchTreeHandler(data) {
		this.isCanCreate = false;
		this.isOperation = true;
		let positionType = 0;
		if(data.id){
			let res = await this.$API.system.position.findById.post({id: data.id});
			if(res && res.code ===2000 ){
				let positionData = res.data;
				if(positionData && positionData.other && positionData.other.isCanCreate == '1'){
					this.isCanCreate = true;
					this.positionType = positionData.other.positionType;
				}
				if(positionData && positionData.other && positionData.other.positionType){
					positionType = parseInt(positionData.other.positionType);
				}
				if(positionType >= 1){
					this.isOperation = false;
				}
				this.lastLevelAddress = res.data.positionAddress;
			}
		}
		this.parentLevelCode = data.levelCode;
		let queryParams = {pathCode: this.parentLevelCode}
		await this.$refs.table.refresh(queryParams);
    },
    async searchHandler() {
      let queryParams = {pathCode: this.parentLevelCode}
      await this.$refs.table.refresh(queryParams);
    },
    columnClickHandler(name,data){
      this.$options.methods[name](this, data);
    },
    //添加
    add(_this) {
      let parentCode;
      let selections = _this.$refs.table.selections();
      if(selections.length>0){
		  let positionTypeNumner = parseInt(selections[0].other.positionType) +1;
		  if(selections[0] && selections[0].other && selections[0].other.isCanCreate == '1'){
			  this.isCanCreate = true;
			  let data = {
				  other:{
					  isCanCreate: '1',
					  positionType: positionTypeNumner +'',
				  },
				  positionAddress: selections[0].positionAddress,
				  parentLevelCode: selections[0].levelCode,
				  entityName:_this.$CONSTANT.entity.FamsPosition.name,
			  };
			  _this.$nextTick(() => {
				  _this.$refs.saveDialog.open(data);
			  })
		  }else {
			  _this.$message.warning("只有区级以及子节点才能添加位置");
			  return;
		  }
      }else{
        parentCode = _this.parentLevelCode;
		  if(!_this.isCanCreate){
			  _this.$message.warning("只有区级以及子节点才能添加位置");
			  return;
		  }
		  let positionTypeNumner = parseInt(_this.positionType)+1;
		  let data = {
			  other:{
				  isCanCreate: '1',
				  positionType: positionTypeNumner + '',
			  },
			  parentLevelCode: parentCode,
			  positionAddress: _this.lastLevelAddress,
			  entityName:_this.$CONSTANT.entity.FamsPosition.name,
		  };
		  _this.$nextTick(() => {
			  _this.$refs.saveDialog.open(data);
		  })
      }

    },
	  //添加
	  adminAdd(_this) {
		  let parentCode;
		  let selections = _this.$refs.table.selections();
		  if(selections.length>0){
			  parentCode = selections[0].levelCode;
		  }else{
			  if(!_this.isOperation){
				  _this.$message.warning("只能在国家省市层级的位置信息新增位置");
				  return;
			  }
			  parentCode = _this.parentLevelCode;
		  }
		  let data = {
			  parentLevelCode: parentCode,
			  entityName:_this.$CONSTANT.entity.FamsPosition.name,
		  };
		  _this.$nextTick(() => {
			  _this.$refs.adminSaveDialog.open(data);
		  })
	  },
    //编辑
    edit(_this) {
      let row = _this.$refs.table.selectionOne();
	  if(row.other && row.other.isNotAction){
		  _this.$message.warning("该位置为系统内置位置，不允许编辑");
		  return;
	  }
      if (!row) {
        return;
      }
      _this.$nextTick(() => {
        _this.$refs.saveDialog.open(row);
      })
    },
      //单个编辑
      detailEdit(_this,row) {
		  if(row.other && row.other.isNotAction){
			  _this.$message.warning("该位置为系统内置位置，不允许编辑");
			  return;
		  }
		  console.log(row)
		  _this.$nextTick(() => {
			_this.$refs.saveDialog.open(row);
		  })
    },
	  //单个编辑
	  adminDetailEdit(_this,row) {
		  if(!(row.other && row.other.isNotAction)){
			  _this.$message.warning("只能编辑国家省市区层级的数据");
			  return;
		  }
		  _this.$nextTick(() => {
			  _this.$refs.adminSaveDialog.open(row);
		  })
	  },
    //单个删除
    detaildel(_this, row) {
      let selections = [];
      selections.push(row);
		if(row.other && row.other.isNotAction){
			_this.$message.warning("该位置为系统内置位置，不允许删除");
			return;
		}
      _this.$confirm(`确定删除选中的位置信息吗？如果该位置中含有子集位置将会被一并删除`, _this.$t('common.warn'), {
        type: 'warning'
      }).then(async () => {

        var delarray = [];
        for (let index = 0; index < selections.length; index++) {
          const element = selections[index];
          delarray.push(element.id);
        }
        var res = await _this.$API.system.position.deleteByIds.post(delarray);
		  if (res.code === 2000) {
			  _this.$message.success(_this.$t("code."+res.code));
			  _this.searchHandler();
			  _this.$store.dispatch("commit",selections[0].entityName);
		  }

      }).catch(() => {

      });
    },

    //查看
    show(_this) {
      let row = _this.$refs.table.selectionOne();
      if (!row) {
        return;
      }
      _this.$nextTick(() => {
        _this.$refs.viewDialog.open(row);
      })
    },
    //查看
    show1(_this,row) {
      _this.$nextTick(() => {
        _this.$refs.viewDialog.open(row);
      })
    },
    //导出
    async export(_this,index) {
      let attachParams = {};
      let exportApi = _this.$API.system.position.export;
      let exTableRef = _this.$refs.table;
      let exportBtnRef = _this.$refs.button;
      let exportBtnIndex = index;
      await BaseTemplate.export(_this, exportApi, attachParams, exportBtnRef, exportBtnIndex, exTableRef);
    },
    //批量删除
    del(_this, index) {
      let selections = _this.$refs.table.selections();
      if (selections.length === 0) {
        _this.$message.warning(_this.$t("common.please_select_data"));
        return;
      }
      _this.$confirm(`确定删除选中的 ${selections.length} 位置吗？如果删除项中含有子集位置将会被一并删除`, _this.$t('common.warn'), {
        type: 'warning'
      }).then(async () => {
        _this.$refs.button.loading(index, true);
        var delarray = [];
        for (let index = 0; index < selections.length; index++) {
          const element = selections[index];
		  if(!(element.other && element.other.isNotAction)){
			  delarray.push(element.id);
		  }
        }
		  if (delarray.length === 0) {
			  _this.$message.warning(_this.$t("common.please_select_data"));
			  return;
		  }
        var res = await _this.$API.system.position.deleteByIds.post(delarray);
		  if (res.code === 2000) {
			  _this.$message.success(_this.$t("code."+res.code));
			  _this.searchHandler();
			  _this.$store.dispatch("commit",selections[0].entityName);
		  }
        _this.$refs.button.loading(index, false);
      }).catch(() => {
        _this.$refs.button.loading(index, false);
      });
    },
    //批量删除
	  adminDelete(_this, index) {
      let selections = _this.$refs.table.selections();
      if (selections.length === 0) {
        _this.$message.warning(_this.$t("common.please_select_data"));
        return;
      }
      _this.$confirm(`确定删除选中的 ${selections.length} 位置吗？如果删除项中含有子集位置将会被一并删除`, _this.$t('common.warn'), {
        type: 'warning'
      }).then(async () => {
        _this.$refs.button.loading(index, true);
        var delarray = [];
        for (let index = 0; index < selections.length; index++) {
          const element = selections[index];
			delarray.push(element.id);
        }
		  if (delarray.length === 0) {
			  _this.$message.warning(_this.$t("common.please_select_data"));
			  return;
		  }
        var res = await _this.$API.system.position.deleteByIds.post(delarray);
		  if (res.code === 2000) {
			  _this.$message.success(_this.$t("code."+res.code));
			  _this.searchHandler();
			  _this.$store.dispatch("commit",selections[0].entityName);
		  }
        _this.$refs.button.loading(index, false);
      }).catch(() => {
        _this.$refs.button.loading(index, false);
      });
    },
    //批量启用
    enabled(_this, index) {
      let selections = _this.$refs.table.selections();
      if (selections.length === 0) {
        _this.$message.warning(_this.$t("common.please_select_data"));
        return;
      }
      _this.$confirm(`确定启用选中的 ${selections.length} 位置吗？`, _this.$t('common.warn'), {
        type: 'warning'
      }).then(async () => {
        _this.$refs.button.loading(index, true);
        var delarray = [];
        for (let index = 0; index < selections.length; index++) {
          const element = selections[index];
          delarray.push(element.id);
        }
        var res = await _this.$API.system.position.enabled.post(delarray);
        if (res.code === 2000) {
          _this.$message.success(_this.$t("code."+res.code));
          _this.searchHandler();
		  _this.$store.dispatch("commit",selections[0].entityName);
        }
        _this.$refs.button.loading(index, false);
      }).catch(() => {
        _this.$refs.button.loading(index, false);
      });
    },
    //批量禁用
    disabled(_this, index) {
      let selections = _this.$refs.table.selections();
      if (selections.length === 0) {
        _this.$message.warning(_this.$t("common.please_select_data"));
        return;
      }
      _this.$confirm(`确定禁用选中的 ${selections.length} 位置吗？`, _this.$t('common.warn'), {
        type: 'warning'
      }).then(async () => {
        _this.$refs.button.loading(index, true);
        var delarray = [];
        for (let index = 0; index < selections.length; index++) {
          const element = selections[index];
          delarray.push(element.id);
        }
        var res = await _this.$API.system.position.disabled.post(delarray);
        if (res.code === 2000) {
          _this.$message.success(_this.$t("code."+res.code));
          _this.searchHandler();
		  _this.$store.dispatch("commit",selections[0].entityName);
        }
        _this.$refs.button.loading(index, false);
      }).catch(() => {
        _this.$refs.button.loading(index, false);
      });
    },
  }
}
</script>
